//
//  ScoreEventViewController.m
//  LiveSoftware
//
//  Created by lanou3g on 15/7/14.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "ScoreEventViewController.h"

//比赛事件
#import "DetailMatchEventModel.h"

//技术统计
#import "DetailTechnologyStatisticsModel.h"


//cell
//比赛 事件   cell
#import "ScoreEventViewCell.h"
//技术分析
#import "TechnologyStatisticsViewCell.h"

//主队事件
#import "HomeEventViewCell.h"

#import "AwayEventViewCell.h"




@interface ScoreEventViewController ()
@property(nonatomic,strong)UIView* noDataView;

//解析出来的数据
@property(nonatomic,copy)NSString *scoreData;

//事件Key
@property(nonatomic,strong)NSMutableArray  *detailMatchEventKeysNameArray;

//技术统计Key
@property(nonatomic,strong)NSArray *DetailTechnologyStatisticsKeysNameArray;




/**
 *事件ModelArray--总得
 */
@property(nonatomic,strong)NSMutableArray *totalDetailMatchEventModelArray;
/**
 *事件ModelArray---主队
 */
@property(nonatomic,strong)NSMutableArray *homeDetailMatchEventModelArray;

/**
 *事件ModelArray---客队
 */
@property(nonatomic,strong)NSMutableArray *awayDetailMatchEventModelArray;


/**
 *技术分析ModelArray
 */
@property(nonatomic,strong)NSMutableArray *technologyStatisticsModelArray;


@property(nonatomic)BOOL isHasScoreEvent;//是否有事件
@property(nonatomic)BOOL isHasTechnologyStatistics;//是否有技术分析
@end

@implementation ScoreEventViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.detailMatchEventKeysNameArray =[@[@"teamType",@"ballType",@"time",@"people"]mutableCopy];
    
    
    self.DetailTechnologyStatisticsKeysNameArray = @[@"eventType",@"homeEventTime",@"awayEventTime"];
    
    
    self.totalDetailMatchEventModelArray = [NSMutableArray array];
    self.homeDetailMatchEventModelArray = [NSMutableArray array];
    
    self.awayDetailMatchEventModelArray = [NSMutableArray array];
    
    self.technologyStatisticsModelArray = [NSMutableArray array];
    
    
    
    [self JieXiScoreEvent];
    
    
    
    // 添加空白的 footView , 防止界面显示不全
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenIp6(5))];
    self.tableView.tableFooterView = footerView;
    
    
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 设置 tableView 不能拖动
    self.tableView.scrollEnabled = NO;
}


#pragma mark //比赛事件


//现在的秒数

-(NSString *)getMiaoShu
{
    
    NSDate *today = [NSDate date];
    
    double dureen = [today timeIntervalSince1970];
    
    NSString *timeString = [NSString stringWithFormat:@"%f",dureen];
    
    
    NSString* miao = [[timeString componentsSeparatedByString:@"."]objectAtIndex:0];
    NSString *haomiao = [[timeString componentsSeparatedByString:@"."]objectAtIndex:1];
    
    NSString *subHaomiao =[haomiao substringToIndex:3];
    
    NSString * totalTime = [NSString stringWithFormat:@"%@%@",miao,subHaomiao];
    return totalTime;
    
}

#pragma mark  解析事件
-(void)JieXiScoreEvent
{
    NSString *urlString = [NSString stringWithFormat:@"http://apk.win007.com/phone/ResultDetail.aspx?ID=%@&lang=0&ran=%@", self.matchID ,[self getMiaoShu ] ];
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    //异步解析
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
    
    
    [urlRequest addValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue]completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
     {
         if(data ==nil || response ==nil )
         {
             return ;
         }
         
         self.scoreData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
         
         [self  divisionResultEventData];
         
         [self.tableView reloadData];
         
#pragma mark - 解析完数据, 刷新表视图之后, 发送通知
         [[NSNotificationCenter defaultCenter] postNotificationName:@"eventFinish" object:nil];
     }];
    
    
    
    
}

//分割字符串
-(void)divisionResultEventData
{
    NSLog(@"----ResultEventData-----self.scoreData---%@",self.scoreData);
    if(self.scoreData != nil  && self.scoreData.length != 0)
    {
        NSArray *first = [self.scoreData componentsSeparatedByString:@"$$"];
        
        
        if(first[0]!=nil  &&  [[first  objectAtIndex:0 ]length]!= 0)
        { //比赛事件
            
            
            NSArray *matchEvent = [first[0] componentsSeparatedByString:@"!"];
            
            for (NSString *group in matchEvent)
            {
                
                NSArray *everyRow = [group componentsSeparatedByString:@"^"];
                //判断everyRow的count,看看是否有名字
                if(everyRow.count !=4)
                {
                    [self.detailMatchEventKeysNameArray removeLastObject];
                    
                }
                
                
                NSDictionary *rowDict = [NSDictionary dictionaryWithObjects:everyRow forKeys:self.detailMatchEventKeysNameArray];
                
                
                
                DetailMatchEventModel *model = [DetailMatchEventModel DetailMatchEventModelWithDict:rowDict];
                
                [self.totalDetailMatchEventModelArray addObject:model];
                
            }
            
#pragma mark  这样判断更加准确
            if(self.totalDetailMatchEventModelArray.count !=0)
            {
                self.isHasScoreEvent = YES;
                
            }
            
            
            
        }
        
        if(first[1]!=nil && ([[first  objectAtIndex:1 ]length]!= 0))
        {
            //技术统计
            //将里面的分别区出来
            NSArray *technologyStatistics = [first[1] componentsSeparatedByString:@"!"];
            
            for (NSString *group in technologyStatistics)
            {
                NSArray *everyRow = [group componentsSeparatedByString:@"^"];
                
                NSDictionary *rowDict = [NSDictionary dictionaryWithObjects:everyRow forKeys:self.DetailTechnologyStatisticsKeysNameArray];
                
                DetailTechnologyStatisticsModel *model = [DetailTechnologyStatisticsModel   DetailTechnologyStatisticsModelWithDict:rowDict];
                [self.technologyStatisticsModelArray addObject:model];
                
                
                
            }
            
            if(self.technologyStatisticsModelArray.count!=0)
            {
                
                self.isHasTechnologyStatistics = YES;
                
                
            }
            
            
        }
        
    }
    
    
    [self addAndRemoveView];
    
    
}



- (NSInteger)numberofSection
{
    int num = 0;
    if (self.isHasScoreEvent)
        
    {
        num = num +1;
    }
    
    if (self.isHasTechnologyStatistics)
    {
        num = num +1;
    }
    
    NSLog(@"-----num---- %d",num);
    
    
    
    return num;
    
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    SectionHeaderView *headerView = [[SectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenIp6(30))];
    
    if(section ==0)
    {
        if(self.isHasScoreEvent)
        {
            headerView.headerLabel.text = @"比赛事件";
        }
        else
        {
            headerView.headerLabel.text = @"赛事技术统计";
        }
        
        
    }
    
    else
    {
        headerView.headerLabel.text = @"赛事技术统计";
    }
    
    return headerView;
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kScreenIp6(30);
}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return [self numberofSection];
}




-(void)addAndRemoveView
{
    
    
    
    
    if(   [self numberofSection]==0 )
    {
        
        
        self.noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        self.noDataView.backgroundColor = [UIColor whiteColor];
        
        
        
        UIImageView *pointPicture = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenWidth/2 - kScreenIp6(100), kScreenIp6(100), kScreenIp6(200), kScreenIp6(200))];
        pointPicture.image = [UIImage imageNamed:@"Empty_Hint_ZZZ@2x"];
        
        [ self.noDataView addSubview:pointPicture];
        
        
        [self.view addSubview: self.noDataView];
        
        
    }
    else
    {
        
        
        [ self.noDataView removeFromSuperview];
        
    }
    
    
    
    
}








- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    if(section == 0)
    {
        if (self.isHasScoreEvent)//
        {
            return self.totalDetailMatchEventModelArray.count +1;
            
        }
        else
        {
            return self.technologyStatisticsModelArray.count;
            
        }
        
        
    }
    else
    {
        
        return self.technologyStatisticsModelArray.count;
        
    }
    
    
    
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    if (indexPath.section == 0)
    {
        
        if(self.isHasScoreEvent)
        {
            
            
            
            
            if(indexPath.row < self.totalDetailMatchEventModelArray.count)
            {
                
                
                DetailMatchEventModel*model = self.totalDetailMatchEventModelArray[indexPath.row];
                
                
                if([model.teamType isEqualToString:@"1"])//1主  ,主队的
                {
                    
                    static NSString *cellIndetifier = @"homeEvent";
                    [tableView registerClass:[HomeEventViewCell class] forCellReuseIdentifier:cellIndetifier];
                    
                    HomeEventViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndetifier forIndexPath:indexPath];
                    
                    
                    [cell setCellValue:model];
                    cell.textLabel.textAlignment = NSTextAlignmentCenter;
                    cell.textLabel.font = [UIFont systemFontOfSize:13];
                    return cell;
                }
                else //客队的
                {
                    static NSString *cellIndetifier = @"awayEvent";
                    [tableView registerClass:[AwayEventViewCell class] forCellReuseIdentifier:cellIndetifier];
                    
                    AwayEventViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndetifier forIndexPath:indexPath];
                    
                    
                    [cell setCellValue:model];
                    return cell;
                    
                }
                
            }
            
            
            else
            {
                
                
                static NSString *cellIndetifier = @"scoreEvent";
                [tableView registerClass:[ScoreEventViewCell class] forCellReuseIdentifier:cellIndetifier];
                
                ScoreEventViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndetifier forIndexPath:indexPath];
                
                return cell;
                
                
            }
            
            
        }
        
        
        
        else  //只有一个分区,如果没有事件,那么就是赛事技术统计
        {
            static NSString *cellIndetifier = @"TechnologyStatisticsViewCell";
            [tableView registerClass:[TechnologyStatisticsViewCell class] forCellReuseIdentifier:cellIndetifier];
            
            TechnologyStatisticsViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndetifier forIndexPath:indexPath];
            
            DetailTechnologyStatisticsModel*model = self.technologyStatisticsModelArray[indexPath.row];
            
            [cell setCellValue:model];
            
            
            return cell;
            
        }
        
    }
    
    else //有两个分区,第一个分区是事件,那么这个就是赛事技术统计
    {
        static NSString *cellIndetifier = @"TechnologyStatisticsViewCell";
        [tableView registerClass:[TechnologyStatisticsViewCell class] forCellReuseIdentifier:cellIndetifier];
        
        TechnologyStatisticsViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndetifier forIndexPath:indexPath];
        
        DetailTechnologyStatisticsModel*model = self.technologyStatisticsModelArray[indexPath.row];
        
        [cell setCellValue:model];
        
        
        return cell;
        
        
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 35;
}




@end
